<template>
  <div style="margin: 0 10px">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
                 label-width="68px">
          <el-form-item label="用户账号" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户账号"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入用户昵称"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']">新建子账户
            </el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="userList">
          <el-table-column label="用户ID" align="center" prop="userId"/>
          <el-table-column label="用户账号" align="center" prop="userName"/>
          <el-table-column label="用户昵称" align="center" prop="nickName"/>
          <el-table-column label="手机号码" align="center" prop="phonenumber"/>
          <el-table-column label="余额" align="center" prop="balance"/>
          <el-table-column label="账号状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="openRecharg(scope.row)">充值
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['system:user:resetPwd']">重置密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"/>
      </el-col>
    </el-row>
    <el-dialog title="添加子账户" :visible.sync="open" width="600px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户账号" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="充值额">
              <el-input v-model="form.balance" type="number"
                        :placeholder="'请输入充值额（总账户最多可分配余额: '+balance+'）'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="充值" :visible.sync="rechargeOpen" :close-on-click-modal="false">
      <div>
        <h3>充值账户：{{ rechargeUserName }}</h3>
        <el-input v-model="rechargNum" :placeholder="'请输入充值额（总账户最多可分配余额: '+balance+'）'" type="number"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="recharg()">确 定</el-button>
        <el-button @click="rechargeOpen=false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import {
    listUserByParent,
    addUser,
    resetUserPwd,
    changeUserStatus,
    getBalance,
    addBalance
  } from "@/api/system/user";

  export default {
    name: "account",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 用户表格数据
        userList: null,
        // 是否显示弹出层
        balance: undefined,
        open: false,

        rechargeOpen: false,
        rechargeUserId: undefined,
        rechargeUserName: undefined,
        rechargNum: undefined,

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userName: undefined,
          nickName: undefined,
          phonenumber: undefined
        },
        // 表单参数
        form: {},

        // 表单校验
        rules: {
          userName: [
            {required: true, message: "账号不能为空", trigger: "blur"},
            {min: 5, max: 20, message: '账号长度必须介于 5 和 20 之间', trigger: 'blur'}
          ],
          password: [
            {required: true, message: "账号密码不能为空", trigger: "blur"},
            {min: 5, max: 20, message: '账号密码长度必须介于 5 和 20 之间', trigger: 'blur'},
            {pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur"}
          ],
          phonenumber: [
            {required: true, message: "手机号不能为空", trigger: "blur"},
            {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号", trigger: "blur"}
          ]
        }
      }
    },
    created() {
      this.getList();
      getBalance().then(res => {
        this.balance = res.data
      })
    },
    methods: {
      openRecharg(item) {
        this.rechargeUserId = item.userId
        this.rechargeUserName = item.userName
        this.rechargeOpen = true
      },
      recharg() {
        if (this.rechargNum > this.balance) {
          this.$modal.msgWarning("分配（充值）的金额要小于总账号余额" + this.balance);
          return
        }
        addBalance({
          userId: this.rechargeUserId,
          recharge: this.rechargNum
        }).then(response => {
          if (response.code == 200) {
            this.$modal.msgSuccess('充值成功');
            this.getList();
            this.rechargeOpen = false;
          }
        });
      },
      /** 查询用户列表 */
      getList() {
        this.loading = true;
        listUserByParent(this.queryParams).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要' + text + row.userName + '用户吗？').then(function () {
          return changeUserStatus({userId: row.userId, status: row.status})
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          nickName: undefined,
          userName: undefined,
          password: undefined,
          phonenumber: undefined,
          balance: undefined,
          parent: this.$store.state.user.id,
          roleId: 3
        }
        this.resetForm("form")
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
          inputValidator: (value) => {
            if (/<|>|"|'|\||\\/.test(value)) {
              return "不能包含非法字符：< > \" ' \\\ |"
            }
          },
        }).then(({value}) => {
          resetUserPwd(row.userId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          })
        })
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.balance > this.balance) {
              this.$modal.msgWarning("分配（充值）的金额要小于总账号余额" + this.balance);
              return
            }
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        })
      }
    }
  };
</script>
